import React, { Component } from 'react';
import { Form, Row, Col, Input, message, Button } from 'antd';
import { connect } from 'dva';
const COUNT_DOWN_TIMES = 60;
const FormItem = Form.Item;

@connect()
class LoginWithMsgFormItem extends Component {
  static defaultProps = {
    id: 'validCode',
    validField: 'account',
    disabled: false,
    focus: false,
    //默认获取手机验证码
    type: 'mobile',
  };

  constructor(props) {
    super(props);
    this.state = {
      time: 0,
      tipVisible: false,
    };

    this.codeInput = React.createRef();
  }

  mounted = true;
  getYCode = e => {
    e && e.preventDefault();
    const { account, dispatch, type } = this.props;
    this.setState({
      time: COUNT_DOWN_TIMES,
    });
    let values;
    let actionType;
    if (type === 'mobile') {
      actionType = 'global/getCodeByMobile';
      values = {
        mobile: account,
        // type4:忘记密码
        type: 4,
      };
    }
    if (type === 'mail') {
      actionType = 'global/getCodeByMail';
      values = {
        email: account,
      };
    }
    dispatch({
      type: actionType,
      payload: values,
    })
      .then(() => {
        // message.success('验证码发送成功');
        this.setState({
          tipVisible: true,
        });
      })
      .catch(err => {
        if (!this.mounted) return;
        message.error(`${err}`);
      });

    const timer = setInterval(() => {
      if (this.mounted && this.state.time > 0) {
        this.setState(({ time }) => ({ time: --time }));
      } else {
        clearInterval(timer);
      }
    }, 1000);
  };

  componentDidMount() {
    if (this.props.focus) this.codeInput.focus();
    this.getYCode();
  }

  componentWillUnmount() {
    this.mounted = null;
  }

  render() {
    const {
      form: { getFieldDecorator },
      id,
      disabled,
      account,
    } = this.props;
    const { time, tipVisible } = this.state;
    const buttonDisabled = time !== 0 || disabled;
    return (
      <>
        {tipVisible && <p>已发送验证码到{account}</p>}
        <Row gutter={10}>
          <Col span={14}>
            <FormItem>
              {getFieldDecorator(id, {
                rules: [
                  {
                    required: true,
                    message: '请输入验证码',
                  },
                  {
                    len: 6,
                    message: '请输入6位验证码',
                  },
                ],
              })(
                <Input
                  className="login-input"
                  disabled={disabled}
                  placeholder="请输入验证码"
                  ref={ref => (this.codeInput = ref)}
                />
              )}
            </FormItem>
          </Col>
          <Col span={10}>
            <Button onClick={this.getYCode} disabled={buttonDisabled} style={{ marginTop: 4 }}>
              {time === 0 ? '获取验证码' : `${time}s后重新发送`}
            </Button>
          </Col>
        </Row>
      </>
    );
  }
}
export default LoginWithMsgFormItem;
